package com.ruoyi.business.controller;

import com.ruoyi.business.domain.ImportData;
import com.ruoyi.business.service.IImportDataService;
import com.ruoyi.business.vo.ExperimentTimeRangeVO;
import com.ruoyi.business.vo.ImportDataGroupVO;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.poi.ExcelUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 导入数据Controller
 * 
 * @author qiancheng
 * @date 2025-09-15
 */
@RestController
@RequestMapping("/business/importData")
public class ImportDataController extends BaseController
{
    @Autowired
    private IImportDataService importDataService;

    /**
     * 查询导入数据列表
     */
    @Anonymous
    @GetMapping("/list")
    public TableDataInfo list(ImportData importData)
    {
        startPage();
        List<ImportData> list = importDataService.selectImportDataList(importData);
        return getDataTable(list);
    }

    /**
     * 导出导入数据列表
     */
    @PreAuthorize("@ss.hasPermi('business:data:export')")
    @Log(title = "导入数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ImportData importData)
    {
        List<ImportData> list = importDataService.selectImportDataList(importData);
        ExcelUtil<ImportData> util = new ExcelUtil<ImportData>(ImportData.class);
        util.exportExcel(response, list, "导入数据数据");
    }

    /**
     * 获取导入数据详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:data:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(importDataService.selectImportDataById(id));
    }

    /**
     * 新增导入数据
     */
    @PreAuthorize("@ss.hasPermi('business:data:add')")
    @Log(title = "导入数据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ImportData importData)
    {
        return toAjax(importDataService.insertImportData(importData));
    }

    /**
     * 修改导入数据
     */
    @PreAuthorize("@ss.hasPermi('business:data:edit')")
    @Log(title = "导入数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ImportData importData)
    {
        return toAjax(importDataService.updateImportData(importData));
    }

    /**
     * 删除导入数据
     */
    @PreAuthorize("@ss.hasPermi('business:data:remove')")
    @Log(title = "导入数据", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(importDataService.deleteImportDataByIds(ids));
    }

    /**
     * 导入数据
     */
    @Anonymous
    @PostMapping("/data")
    public AjaxResult importData(@RequestParam("file") MultipartFile file,
                                 @RequestParam("type") Integer type,
                                 @RequestParam("importDay") @DateTimeFormat(pattern = "yyyy-MM-dd") Date importDay,
                                 @RequestParam("startTime") String startTime,
                                 @RequestParam("endTime") String endTime,
                                 @RequestParam(value = "updateSupport", defaultValue = "true") boolean updateSupport) throws Exception
    {
        // 先校验模板
        validateTemplateType(file, type);

        ExcelUtil<ImportData> util = new ExcelUtil<>(ImportData.class);
        List<ImportData> rawList = util.importExcel(file.getInputStream());

        if (rawList == null || rawList.isEmpty()) {
            throw new ServiceException("Excel 文件为空或解析失败！");
        }

        for (ImportData data : rawList) {
            data.setType(type);
            data.setImportDay(importDay);
            data.setStartTime(startTime.trim());
            data.setEndTime(endTime.trim());
            switch (type) {
                case 1: // 均匀性
                    data.setField1(data.getCylNo());
                    data.setField2(data.getLiquidHeight());
                    break;
                case 2: // 热学
                    data.setField1(data.getPlateTemp());
                    data.setField2(data.getHeatTransferCoef());
                    break;
                case 3: // 热流
                    data.setField1(data.getTimeS());
                    data.setField2(data.getSurfaceHeatFlux());
                    break;
            }
        }


        String message = importDataService.importImportData(rawList, updateSupport);
        return AjaxResult.success(message);
    }

    /**
     * 模版校验
     * @param file
     * @param type
     * @throws Exception
     */
    public void validateTemplateType(MultipartFile file, Integer type) throws Exception {
        Workbook workbook = WorkbookFactory.create(file.getInputStream());
        Sheet sheet = workbook.getSheetAt(0);

        Row headerRow = sheet.getRow(0);
        if (headerRow == null) {
            throw new ServiceException("Excel 文件表头为空！");
        }

        List<String> headers = new ArrayList<>();
        for (Cell cell : headerRow) {
            headers.add(cell.getStringCellValue().trim());
        }

        switch (type) {
            case 1: // 均匀性
                if (!headers.containsAll(Arrays.asList("量筒编号", "液位高度"))) {
                    throw new ServiceException("Excel 文件不符合均匀性模板，请使用正确模板！");
                }
                break;
            case 2: // 热学
                if (!headers.containsAll(Arrays.asList("钢板温度", "表面换热系数"))) {
                    throw new ServiceException("Excel 文件不符合热学模板，请使用正确模板！");
                }
                break;
            case 3: // 热流
                if (!headers.containsAll(Arrays.asList("时间", "钢板表面热流"))) {
                    throw new ServiceException("Excel 文件不符合热流模板，请使用正确模板！");
                }
                break;
            default:
                throw new ServiceException("未知 type 类型！");
        }
    }

    @Anonymous
    @ApiOperation("根据类型获取导入时间列表")
    @GetMapping("/importTimes")
    public AjaxResult getImportTimes(@RequestParam Integer type) {
        List<String> times = importDataService.getImportTimesByType(type);
        return AjaxResult.success(times);
    }

    @Anonymous
    @ApiOperation("根据导入时间获取实验时间范围")
    @GetMapping("/timeRange")
    public TableDataInfo getTimeRange(@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date importDay,
                                   @RequestParam Integer type) {
        List<ExperimentTimeRangeVO> timeRangeByImportTime = importDataService.getTimeRangeByImportTime(importDay, type);
        return getDataTable(timeRangeByImportTime);
    }


    /**
     * 下载导入模板
     *
     * @param type 数据类型：1=液位，2=热学，3=热流
     */
    @Anonymous
    @GetMapping("/downloadTemplate")
    public void downloadTemplate(@RequestParam("type") Integer type, HttpServletResponse response) throws IOException {
        importDataService.downloadTemplate(type, response);
    }

    /**
     * 按类型分组查询导入数据
     * @param types 可选，数据类型列表
     * @param field1 可选，字段1过滤
     * @param field2 可选，字段2过滤
     * @param importDay 可选，导入日期过滤
     * @param startTime 可选，开始时间过滤
     * @param endTime 可选，结束时间过滤
     * @return 按 type 分组的导入数据 VO 列表
     */
    @Anonymous
    @ApiOperation("按类型分组获取导入数据")
    @GetMapping("/groupedList")
    public AjaxResult groupedList(@RequestParam(required = false) String types,
                                  @RequestParam(required = false) String field1,
                                  @RequestParam(required = false) String field2,
                                  @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date importDay,
                                  @RequestParam(required = false) String startTime,
                                  @RequestParam(required = false) String endTime) {

        List<ImportDataGroupVO> result = importDataService.selectImportDataGroupedByTypes(types, field1, field2, importDay, startTime, endTime);
        return AjaxResult.success(result);
    }

    /**
     * 富氧四级页面
     * @param types 可选，数据类型列表  1：常规燃烧特性 2：纯氧燃烧特性-氮氧化物 3：纯氧燃烧特性-火焰长度 4：富氧燃烧特性
     * @param importDay 可选，导入日期过滤
     * @param startTime 可选，开始时间过滤
     * @param endTime 可选，结束时间过滤
     * @return 按 type 分组的导入数据 VO 列表
     */
    @Anonymous
    @GetMapping("/queryCombustionProperties")
    public AjaxResult queryCombustionProperties(@RequestParam(required = false) String types,
                                  @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date importDay,
                                  @RequestParam(required = false) String startTime,
                                  @RequestParam(required = false) String endTime) {

        List<ImportDataGroupVO> result = importDataService.queryCombustionProperties(types, importDay, startTime, endTime);
        return AjaxResult.success(result);
    }

    /**
     * 立式四级页面
     * @param types 可选，数据类型列表  1：NOX 2：PV
     * @param importDay 可选，导入日期过滤
     * @param startTime 可选，开始时间过滤
     * @param endTime 可选，结束时间过滤
     * @return 按 type 分组的导入数据 VO 列表
     */
    @Anonymous
    @GetMapping("/getVertFourthInfo")
    public AjaxResult getVertFourthInfo(@RequestParam(required = false) String types,
                                                @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date importDay,
                                                @RequestParam(required = false) String startTime,
                                                @RequestParam(required = false) String endTime) {

        List<ImportDataGroupVO> result = importDataService.getVertFourthInfo(types, importDay, startTime, endTime);
        return AjaxResult.success(result);
    }

}
